package com.matt.repository;

import com.matt.controller.api.domin.Thermometer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


public interface ThermometerRepository extends JpaRepository<Thermometer, String>, JpaSpecificationExecutor<Thermometer> {

    @Query(value = "select hl_thermometer.* from hl_thermometer where hl_thermometer.areaId=?1 ORDER BY hl_thermometer.createTime DESC limit 1", nativeQuery = true)
    Thermometer findAllByLimitThermometer(String areaId);

    @Query(value = "select hl.* from hl_thermometer hl where hl.areaId=?1 and deviceId=?2 ORDER BY hl.createTime DESC limit 1", nativeQuery = true)
    Thermometer findAllByLimitThermometer1(String areaId, Long deviceId);

    @Modifying
    @Transactional
    @Query(value = "DELETE FROM hl_thermometer WHERE hl_thermometer.createTime < ?1 - INTERVAL 7 DAY", nativeQuery = true)
    void deleteAllByRecordIdThreeDaysAgo(LocalDateTime threeDaysAgo);
}
